/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.cli;

import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.Repository;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class AutomaticTransformationsAction extends Action {

    private static final Set<MetadataFormat> supportedFormats = new HashSet<MetadataFormat>();
    private MetadataFormat sourceFormat = null;
    private MetadataCollection selectedCollection = null;
    private boolean allCollections = false;

    static {
        supportedFormats.add(MetadataFormat.marc21);
        supportedFormats.add(MetadataFormat.tei_p5);
    }

    public AutomaticTransformationsAction(Repository repository, String metadataFormat, String collectionName) throws Exception {
        super(repository);
        sourceFormat = MetadataFormat.parseString(metadataFormat);
        checkIfFormatSupported();
        determineCollection(collectionName);
    }

    @Override
    public void run() throws Exception {
        if (allCollections) {
            runForAllCollections();
        } else {
            runForCollection();
        }
    }

    private void checkIfFormatSupported() throws Exception {
        for (MetadataFormat supported : supportedFormats) {
            if (sourceFormat == supported) {
                return;
            }
        }
        throw new Exception("metadata format " + sourceFormat.toString() + " is not supported for automatic recreation");
    }

    private void determineCollection(String collectionName) throws Exception {
        CollectionParser collectionParser = new CollectionParser(repository, collectionName);
        allCollections = collectionParser.allCollections();
        selectedCollection = collectionParser.getCollection();
    }

    private void runForAllCollections() throws IOException {
        for (MetadataCollection collection : repository.getCollections()) {
            repository.updateDerivedRecords(collection, sourceFormat);
        }
    }

    private void runForCollection() throws IOException {
        repository.updateDerivedRecords(selectedCollection, sourceFormat);
    }
}
